package com.youmeek.ssm.basic.common.memcache;

import com.youmeek.ssm.basic.common.cache.CacheClient;
import net.rubyeye.xmemcached.MemcachedClient;

public class MemcachedCacheClient implements CacheClient {

    private final MemcachedClient memcachedClient;

    public MemcachedCacheClient(MemcachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }

    @Override
    public <T> T get(String key) {
        T value = null;

        try {
            value = memcachedClient.get(key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return value;
    }

    @Override
    public void put(String key, Object value) {
        if (value == null) {
            return;
        }

        this.put(key, 0, value);
    }

    @Override
    public void put(String key, int exp, Object value) {
        if (value == null) {
            return;
        }

        try {
            memcachedClient.setWithNoReply(key, exp, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(String key) {
        try {
            memcachedClient.deleteWithNoReply(key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
